package com.syf.starter.core.netty.tool.impl;

import cn.hutool.core.util.StrUtil;
import com.syf.core.service.SyServiceDefinition;
import com.syf.core.service.invoke.SyServiceInvoker;
import com.syf.starter.core.netty.tool.SyfServiceRoute;
import io.netty.handler.codec.http.FullHttpRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

@Slf4j
public class HttpUriRoute implements SyfServiceRoute<FullHttpRequest> {
    private String uriPattern;

    private AntPathMatcher pathMatcher;

    public HttpUriRoute(String webContext) {
        if (StrUtil.isBlank(webContext) || "/".equals(webContext)) {
            uriPattern = "/service/{serviceCode}.do";
        } else {
            uriPattern = "/" + webContext + "/service/{serviceCode}.do";
        }

        this.pathMatcher = new AntPathMatcher();
    }

    @Override
    public SyServiceDefinition route(FullHttpRequest request, SyServiceInvoker serviceInvoker) {
        String reqUri = request.uri();
        String[] split = reqUri.split("\\?");
        reqUri = split[0];

        int index = reqUri.indexOf(".do");
        if (index != -1) {
            reqUri = reqUri.substring(0, index + 3);
        }

        String serviceCode = null;
        if (pathMatcher.match(uriPattern, reqUri)) {
            serviceCode = pathMatcher.extractUriTemplateVariables(uriPattern, reqUri).get("serviceCode");
            if (StrUtil.isBlank(serviceCode) || !serviceInvoker.isExistService(serviceCode)) {
                log.error("未找到serviceCode:[{}]对应的交易!", serviceCode);
                return null;
            }

            return serviceInvoker.getDefinition(serviceCode);
        }

        log.error("uri:[{}]格式不正确，无法获取对应的交易码!URI Pattern是{}", reqUri, uriPattern);
        return null;
    }
}
